package com.lxk.seckilldemo.rabbitMQ;

import com.alibaba.fastjson.JSON;
import com.lxk.seckilldemo.pojo.SeckillMessage;
import com.lxk.seckilldemo.pojo.SeckillOrder;
import com.lxk.seckilldemo.pojo.User;
import com.lxk.seckilldemo.service.IGoodsService;
import com.lxk.seckilldemo.service.IOrderService;
import com.lxk.seckilldemo.service.ISeckillOrderService;
import com.lxk.seckilldemo.vo.GoodsVo;
import com.lxk.seckilldemo.vo.RespBean;
import com.lxk.seckilldemo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class Reciver {
//    @RabbitListener(queues = "queue")
//    public void receive(Object msg){
//        log.info("接受消息："+msg);
//    }
//    @RabbitListener(queues="queue_fanout01")
//    public void receive01(Object msg){
//        log.info("QUEUE01接收消息："+msg);
//    }
//    @RabbitListener(queues ="queue_fanout02")
//    public void receive02(Object msg) {
//        log.info("QUEUE02接收消息："+msg);
//    }
//    @RabbitListener(queues="queue_direct01")
//    public void receiveDi01(Object msg){
//        log.info("QUEUE01接收消息："+msg);
//    }
//    @RabbitListener(queues ="queue_direct02")
//    public void receiveDi02(Object msg) {
//        log.info("QUEUE02接收消息："+msg);
//    }
//    @RabbitListener(queues="queue_topic01")
//    private void receive05(Object msg) {
//        log.info("QUEUE01接收消息："+msg);
//    }
//    @RabbitListener(queues="queue_topic02")
//    private void receive06(Object msg){
//        log.info("QUEUE02接收消息："+msg);
//    }


    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IOrderService orderService;
    @RabbitListener(queues = "seeckollqueue")
    public void receive(String msg){
        log.info("接受消息："+msg);
        SeckillMessage seckillMessage=JSON.parseObject(msg, SeckillMessage.class);
        User user=seckillMessage.getUser();
        Long goodsId=seckillMessage.getGoodId();
        GoodsVo goodsVo=goodsService.findGoodsVoById(goodsId);
        if(goodsVo.getGoodsStock()<1){
            return;
        }
        //判断是否重复抢购
        ValueOperations va=redisTemplate.opsForValue();
        SeckillOrder seckillOrder = (SeckillOrder)va.get("order:"+user.getId()+":"+goodsVo.getId());
        if(seckillOrder!=null){
            return;
        }
        //下单
        orderService.secKill(user,goodsVo);
    }
}
